package com.jhsw.roadsun.module.business.util;

import cn.hutool.core.io.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.io.File;
import java.util.concurrent.locks.ReentrantLock;

@Slf4j
@Component
public class WordToPdfUtil {

    @Value("${libre-office}")
    private String libreOffice;

    // 加锁，为何？因为两条命令同时执行的时候，会有一条不执行
    private static final ReentrantLock CONVERT_LOCK = new ReentrantLock(true);

    public byte[] wordToPdf(File wordFile, String tempZipDir) {
        String wordFilePath = wordFile.getAbsolutePath();
        try {
            // 创建命令行
            String command = libreOffice + " --headless --convert-to pdf --outdir " + tempZipDir + " " + wordFilePath;
            CONVERT_LOCK.lock();
            // 执行命令
            Process process = Runtime.getRuntime().exec(command);

            // 等待命令执行完毕
            process.waitFor();

            return FileUtil.readBytes(tempZipDir + wordFile.getName().replace(".docx", ".pdf"));
        } catch (Throwable e) {
            log.error("Word转Pdf失败：", e);
            return null;
        } finally {
            if (CONVERT_LOCK.isLocked())
                CONVERT_LOCK.unlock();
            FileUtil.del(wordFile);
        }
    }
}
